﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Devices.Geolocation;
using PhoneMap.Common;
using PhoneMap.Model;
using PhoneMap.ViewModel;

namespace PhoneMap
{
    public partial class StartupPage : PhoneApplicationPage
    {
        ProgressIndicator pi;
        LoginViewModel login;
        public StartupPage()
        {
            InitializeComponent();
            pi = new ProgressIndicator();
            pi.IsIndeterminate = true;
            pi.IsVisible = false;
            this.Loaded += StartupPage_Loaded;
        }
        void StartupPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.CheckInternet.IsConnected)
                GetPostion();
            else
                App.CheckInternet.ShowMessageNetwork();
        }
        public async void GetPostion()
        {
            pi.IsVisible = true;
            pi.IsIndeterminate = true;
            pi.Text = "Resolving...";
            SystemTray.SetProgressIndicator(this, pi);
            Geolocator MyGeolocator = new Geolocator();
            MyGeolocator.DesiredAccuracyInMeters = 5;
            try
            {
                App.MyGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Location is disabled in phone settings");
            }
            pi.IsVisible = false;
            pi.IsIndeterminate = false;
            pi.Text = "Complete";
            SystemTray.SetProgressIndicator(this, pi);

            var getDataLogin = await StorageProvider.RestoreObjectsAsync<FacebookData>(StorageProvider.FACEBOOKDATA);
            if (getDataLogin != null)
            {
                App.FacebookDatas = getDataLogin;
                login = new LoginViewModel();
                login.Login(getDataLogin);

            }

            else
                NavigationService.Navigate(new Uri("/View/Login.xaml", UriKind.Relative));
        }
    }
}